package com.hq.aop.log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.eredlab.g4.arm.util.ArmConstants;
import org.eredlab.g4.arm.util.idgenerator.IDHelper;
import org.eredlab.g4.bmf.aop.SpringBeanAspect;
import org.eredlab.g4.bmf.base.IDao;
import org.eredlab.g4.bmf.util.SpringBeanLoader;
import org.eredlab.g4.ccl.datastructure.Dto;
import org.eredlab.g4.ccl.datastructure.impl.BaseDto;
import org.eredlab.g4.ccl.properties.PropertiesFactory;
import org.eredlab.g4.ccl.properties.PropertiesFile;
import org.eredlab.g4.ccl.properties.PropertiesHelper;
import org.eredlab.g4.ccl.util.G4Utils;

/**
 * SpringBean监控切面
 * 
 * @author XiongChun
 * @since 2010-09-21
 */
public class LogFileSave {
	
	private static Log log = LogFactory.getLog(SpringBeanAspect.class);
	private static long count=1;
	/**
	 * Service方法调用通知
	 * synchronized:标记为同步方法主要是为处理开启切面监控时候造成死锁的问题.
	 * @param pjp
	 * @return
	 * @throws Throwable
	 */
	public synchronized Object doServiceAround(ProceedingJoinPoint pjp) throws Throwable 
	{	
		//得到当前时间
		String activeTime = G4Utils.getCurrentTime();
		//得到目标对象的类名，就是被拦截的方法对应的类类名！
		String clazzString = pjp.getTarget().getClass().getName();
		//得到方法签名，并得到方法的名称，这里指被拦截的方法的名字！
		String methodName = pjp.getSignature().getName();
		//通过字符串的连接形成一种类名点方法名的格式！
		String fullPath = clazzString + "." + methodName;
		long time = System.currentTimeMillis();
		//得到要执行的业务对象！
		Object retVal = pjp.proceed();
		time = System.currentTimeMillis() - time;
		saveEabeanMonitorDomain(fullPath+"\t\t\t执行时间为："+time);
		return retVal;
	}

	/**
	 * Service方法异常通知
	 * synchronized:标记为同步方法主要是为处理开启切面监控时候造成死锁的问题.
	 * @param jp
	 * @param ex
	 */
	public synchronized void doServiceThrowing(JoinPoint jp, Throwable ex) {
		String activeTime = G4Utils.getCurrentTime();
		String clazzString = jp.getTarget().getClass().getName();
		String methodName = jp.getSignature().getName();
		String fullPath = clazzString + "." + methodName;
		saveEabeanMonitorDomain(fullPath+"\t\t\t发生了异常！");
	}

	/**
	 * 持久化监控信息
	 * 
	 * @param pEabeanMonitorDomain
	 */
	private void saveEabeanMonitorDomain(String str) {
		try 
		{
			File f=new File("g:\\log.txt");
			if(!f.exists())
			{
				System.out.println("文件不存在，从新建立一个");
				f.createNewFile();
			}
			else
			{
				System.out.println("文件存在！");
			}
			FileWriter out=new FileWriter(f,true);
			BufferedWriter buff=new BufferedWriter(out);
			buff.write(LogFileSave.count+":"+str);
			buff.newLine();
			buff.flush();
			buff.close();
		} 
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
